<template>
	<view class="page">
		<!-- 页面头部内容开始 -->
		<vk-data-page-header
			:title="page.title"
			:show-back="page.showBack"
			@back="pageBack"
		></vk-data-page-header>
		<!-- 页面头部内容结束 -->
		<view class="page-body" v-if="page.complete" v-loading="form1.props.loading">
			<!-- 页面主体内容开始 -->
			<vk-data-form
				ref="form1"
				v-model="form1.data"
				:rules="form1.props.rules"
				:action="form1.props.action"
				:form-type="form1.props.formType"
				:columns='form1.props.columns'
				:loading.sync="form1.props.loading"
				:labelWidth="form1.props.labelWidth"
				:footer-show="false"
				size="small"
				:success-msg="form1.props.successMsg"
				:before-action="form1.props.beforeAction"
				@success="formSuccess"
			>
				<template v-slot:discount_rule="{ form, keyName, column }">
					<view style="color: #606266;font-size: 14px;">
						<view style="display: flex;">
							<text>订单实付金额每满</text>
							<vk-data-input-money v-model="form.discount_rule.a" :precision="2" :max="10000000" width="100px" placeholder="多少" style="margin: 0 10px;" size="small"></vk-data-input-money>
							<text>元，可用</text>
							<vk-data-input-number v-model="form.discount_rule.b" :precision="0" :max="10000000" width="100px" placeholder="多少" style="margin: 0 10px;" size="small"></vk-data-input-number>
							<text>积分抵扣</text>
							<vk-data-input-money v-model="form.discount_rule.c" :precision="2" :max="10000000" width="100px" placeholder="多少" style="margin: 0 10px;" size="small"></vk-data-input-money>
							<text>元</text>
						</view>
						<vk-data-tips :tips="column.tips"></vk-data-tips>
					</view>
				</template>
			</vk-data-form>
			<!-- 页面主体内容结束 -->
		</view>
		<view class="page-footer">
			<!-- 页面底部内容开始 -->
			<el-button v-if="page.showBack" plain style="margin-right: 20px;width: 80px;" @click="pageBack" :loading="form1.props.loading">{{ page.cancelText }}</el-button>
			<el-button type="primary" style="width: 80px;" @click="submitForm" :loading="form1.props.loading">{{ page.submitText }}</el-button>
			<!-- 页面底部内容开始 -->
		</view>
		<view class="page-dialog">
			<!-- 页面弹窗内容开始 -->

			<!-- 页面弹窗内容开始 -->
		</view>
	</view>
</template>

<script>
	var that;													// 当前页面对象
	var vk = uni.vk;									// vk实例
	var settingKey = "integral_rule";
	export default {
		data() {
			// 页面数据变量
			return {
				// init请求返回的数据
				data:{

				},
				page: {
					title: "积分规则",
					submitText: "设置",
					cancelText: "返回",
					showBack: false,
					backPage:"",
					complete: false,
				},
				form1: {
					// 表单请求数据，此处可以设置默认值
					data: {
						enable:false,
						discount_rule:{
							a:"",
							b:"",
							c:"",
						},
						available_range_rule:{
							type:"",
							goods_type:1,
							category_ids:[],
							goods_ids:[],
						},
						disable_vip: false,
						disable_coupon: false,
					},
					// 表单属性
					props: {
						// 表单请求地址
						action: "admin/business/sys/integral.updateSetting",
						// 表单字段显示规则
						columns: [
							{ key: "enable", title: "是否启用积分优惠", type: "switch", activeValue: true, inactiveValue: false , tips:"只有此开关开启后，下面的积分规则才生效。"},
							{ key: "", title: "抵扣规则", type: "bar-title" },
							{ key: "discount_rule", title: "", type: "text",  tips:"注意：订单实付金额只计算可用范围规则内的商品金额，且不含运费。" },
							{ key: "", title: "优惠叠加规则", type: "bar-title" },
							{
								key: "disable_vip", title: "会员折扣", type: "radio", optionType: "button",
								data: [
									{ value: true, label: "禁用" },
									{ value: false, label: "可用" }
								]
							},
							{
								key: "disable_coupon", title: "优惠券", type: "radio", optionType: "button",
								data: [
									{ value: true, label: "禁用" },
									{ value: false, label: "可用" }
								]
							},
							{ key:"", title:"可用范围规则", type:"bar-title" },
							{ key:"available_range_rule", title:"", type:"object", width:100, showLabel:false,
								columns:[
									{
										key:"type", title:"状态", type:"radio",
										data:[
											{ value:0, label:"全部商品可用" },
											{ value:1, label:"指定商品可用" },
											{ value:2, label:"指定商品不可用" }
										]
									},
									{
										key:"goods_type", title:"指定类型", type:"radio",
										data:[
											{ value:0, label:"指定分类" },
											{ value:1, label:"指定商品" },
										],
										showRule:(formData)=>{
											return formData.available_range_rule.type > 0;
										}
									},
									{
										key:"category_ids", title:"商品分类", type:"cascader", width:400,
										action:"admin/business/sys/goodsCategory.kh_getList",
										props:{
											list:"rows",
											value:"_id",
											label:"name",
											children:"children",
											checkStrictly:true,
											emitPath:false,
											multiple:true
										},
										showRule:(formData)=>{
											return formData.available_range_rule.goods_type == 0 && formData.available_range_rule.type > 0;
										},
									},

									{
										key: "goods_ids", title: "选择商品", type: "table-select", placeholder:"请选择商品", showRule:"type>0",
										action:"admin/business/sys/goods.getList",
										multiple:true,
										formData:{
											status:0
										},
										columns:[
										 { key:"goods_thumb", title:"商品图", type:"avatar", imageWidth:40 },
										 { key:"name", title:"商品名称", type:"text", width:160, align:"left" },
										 { key:"categoryList", title:"所属分类", type:"text", width:140, defaultValue:'暂无',
											formatter: (val, row, column, index) => {
												let str = "";
												val.map((item, index) => {
													if (index > 0) str += "、";
													str += item.name;
												});
												return str;
											}
										 },
										 { key:"sku_list", title:"价格区间", type:"text", width:200, defaultValue:'暂无' ,
											formatter:(val, row, column, index) => {
												let a = [];
												val.map((item, index) => {
													a.push(Number(item.price))
												});
												let max = Math.max(...a);
												let min = Math.min(...a);
												if(max != min){
													// 如果最大值和最小值不相等
													return	vk.pubfn.priceFilter(min) +' - '+ vk.pubfn.priceFilter(max);
												}else{
													// 如果最大值和最小值相等
													return  vk.pubfn.priceFilter(min);
												}
											}
										 },
										 { key: "stock", title: "商品库存", type: "number", width: 110, show:["row"]  },
										],
										queryColumns:[
											{ key: "name", type: "text", title:"商品名称", placeholder:"请输入商品名称", width:220, mode:"%%" },
											{
												key:"category_ids", title:"商品分类", type:"cascader", width:250, mode:"in",
												action:"admin/business/sys/goodsCategory.kh_getList",
												props:{
													list:"rows",
													value:"_id",
													label:"name",
													children:"children",
													checkStrictly:true,
													emitPath:false
													// multiple:true
												}
											},
											{ key: "_id", title: "角色标识", type: "text", width: 150, mode: "%%", show:false }
										],
										showRule:(formData)=>{
											return formData.available_range_rule.goods_type == 1 && formData.available_range_rule.type > 0;
										},
									}
								]
							},
						],
						// 表单验证规则
						rules: {
							discount_rule: [
								// 自定义
								{ validator: (rule, value={}, callback)=>{
									let { a, b, c } = value;
									let nullKey = vk.pubfn.isNullOneByObject({ a, b, c });
									if (nullKey) callback(new Error('请完善抵扣规则'));
									if (a <= 0 || b <= 0 || c <= 0) callback(new Error('抵扣规则填写错误：数值必须都大于0'));
									if (c > a) callback(new Error('抵扣规则填写错误：积分抵扣金额不能大于订单金额'));
									callback();
								}, trigger: ['blur','change'] }
							]
						},
						labelWidth: "150px",
						loading:false,
						successMsg:"设置成功",
						beforeAction:(formData)=>{
							// 可在此处修改 formData 后返回 formData，若在此处return false，则表单不触发提交请求。
							return {
								[settingKey]:formData
							};
						},
					}
				},
				goodsSelect:{
					action:"admin/business/sys/goods.getList",
					multiple:true,
					formData:{
						status:0
					},
					columns:[
					 { key:"goods_thumb", title:"商品图", type:"avatar", imageWidth:40 },
					 { key:"name", title:"商品名称", type:"text", width:160, align:"left" },
					 { key:"categoryList", title:"所属分类", type:"text", width:140, defaultValue:'暂无',
						formatter: (val, row, column, index) => {
							let str = "";
							val.map((item, index) => {
								if (index > 0) str += "、";
								str += item.name;
							});
							return str;
						}
					 },
					 { key:"sku_list", title:"价格区间", type:"text", width:200, defaultValue:'暂无' ,
						formatter:(val, row, column, index) => {
							let a = [];
							val.map((item, index) => {
								a.push(Number(item.price))
							});
							let max = Math.max(...a);
							let min = Math.min(...a);
							if(max != min){
								// 如果最大值和最小值不相等
								return	vk.pubfn.priceFilter(min) +' - '+ vk.pubfn.priceFilter(max);
							}else{
								// 如果最大值和最小值相等
								return  vk.pubfn.priceFilter(min);
							}
						}
					 },
					 { key: "stock", title: "商品库存", type: "number", width: 110, show:["row"]  },
					],
					queryColumns:[
						{ key: "name", type: "text", title:"商品名称", placeholder:"请输入商品名称", width:220, mode:"%%" },
						{
							key:"category_ids", title:"商品分类", type:"cascader", width:250, mode:"in",
							action:"admin/business/sys/goodsCategory.kh_getList",
							props:{
								list:"rows",
								value:"_id",
								label:"name",
								children:"children",
								checkStrictly:true,
								emitPath:false
								// multiple:true
							}
						},
						{ key: "_id", title: "角色标识", type: "text", width: 150, mode: "%%", show:false }
					]
				}
			}
		},
		// 监听 - 页面每次【加载时】执行(如：前进)
		onLoad(options = {}) {
			that = this;
			vk = that.vk;
			that.options = options;
			that.init(options);
		},
		// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
		onReady(){

		},
		// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
		onShow() {

		},
		// 监听 - 页面每次【隐藏时】执行(如：返回)
		onHide() {

		},
		// 函数
		methods: {
			// 页面数据初始化函数
			init(options){
				that.$nextTick(() => {
					let mchInfo = vk.getVuex('$user.mchInfo');
					that.initData(mchInfo);
					that.page.complete = true;
					vk.callFunction({
						url: 'client/pub/getMchInfo',
						loading:{ that, name:"form1.props.loading"},
						data:{},
						success:(data) => {
							that.initData(data.mchInfo);
							vk.setVuex('$user.mchInfo',data.mchInfo);
						}
					});
				});
			},
			initData(mchInfo){
				vk.pubfn.objectAssign(this.form1.data, mchInfo[settingKey]);
			},
			// 页面跳转
			pageTo(path){
				vk.navigateTo(path);
			},
			// 页面返回
			pageBack(){
				const pages = getCurrentPages();
				if (pages.length>1 && pages[0].route !== that.$page.route) {
					vk.navigateBack();
				} else if(that.page.backPage) {
					vk.navigateTo(that.page.backPage);
				}
			},
			// 表单重置
			resetForm() {
				that.$refs.form1.resetForm();
			},
			// 表单提交
			submitForm(){
				that.$refs.form1.submitForm();
			},
			// 表单提交成功后的回调
			formSuccess(res){
				vk.setVuex("$user.mchInfo", res.data.mchInfo);
			}
		},
		// 监听器
		watch:{

		},
		// 计算属性
		computed:{

		}
	}
</script>
<style lang="scss" scoped>

</style>
